package javaLearning.Steam流式;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description: 社招题目
 * 对输入的字符串s，忽略大小写，返回按照英文字母出现的频率从高到低的排序的字符串，对于出现次数相同的字母
 * 按照字典序排序。如果输入字符串不包含英文字母则返回空字符串。注意数字标点空格都不是英文字母
 * <p>
 * 输入：We Attack at Dawn
 * 返回：atwcdekn
 * @author: Kk
 * @create: 2020-12-26 10:20
 **/
public class Practice {
    public static void main(String[] args) {
        System.out.println(Practice.mostFrequentLetters2("]]]We23... A...,,,ttack !!121 at Dawn"));
        System.out.println(Practice.mostFrequentLetters1("We Attack at Dawn"));
        System.out.println(Practice.mostFrequentLetters1("cccccaaaassswwqqqq"));
    }

    static String mostFrequentLetters(String s) {
        StringBuilder result = new StringBuilder();
        Stream.of(s.toLowerCase().replaceAll("[^a-z]", "").split(""))
                .collect(Collectors.groupingBy(s1 -> s1.charAt(0), Collectors.counting()))
                .entrySet()
                .stream().sorted((o1, o2) -> {
            if (0 == o1.getValue().compareTo(o2.getValue())) {
                return o1.getKey().compareTo(o2.getKey());
            }
            return o2.getValue().compareTo(o1.getValue());
        })
                .map(Map.Entry::getKey)
                .collect(Collectors.toList())
                .forEach(s1 -> result.append(s1.charValue()));
        return result.toString();
    }

    static String mostFrequentLetters1(String s) {
        //筛选出字母
        Optional<String> reduce = s.chars().mapToObj(i -> (char) i).map(Character::toLowerCase)
                .filter(c -> ('a' <= c) && ('z' >= c))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream().sorted((o1, o2) -> {
                    if (0 == o1.getValue().compareTo(o2.getValue())) {
                        return o1.getKey().compareTo(o2.getKey());
                    }
                    return o2.getValue().compareTo(o1.getValue());
                })
                .map(entry -> entry.getKey().toString())
                .reduce(String::concat);

        return reduce.get();
    }

    static String mostFrequentLetters2(String s) {
        //筛选出字母
        String reduce = s.chars().mapToObj(i -> (char) i).map(Character::toLowerCase)
            .filter(c -> ('a' <= c) && ('z' >= c))
            .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()))
            .entrySet().stream()
            .sorted(Map.Entry.<Character, Long>comparingByValue().reversed().thenComparing(Map.Entry::getKey))
            .flatMap(k-> Stream.of(k.getKey().toString())).collect(Collectors.joining());
        return reduce;
    }
}
